package com.ITXu.reggie.filter;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.AntPathMatcher;

import com.ITXu.reggie.commom.BaseContext;
import com.ITXu.reggie.commom.R;
import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter{
	
	AntPathMatcher pathMatcher = new AntPathMatcher();
	
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
    		throws IOException, ServletException {
    	HttpServletRequest request = (HttpServletRequest)servletRequest;
    	HttpServletResponse response = (HttpServletResponse)servletResponse;
    	//1. 获取本次请求的URI
    	log.info("拦截到请求:{}", request.getRequestURI());
    	String uri = request.getRequestURI();
    	//2. 判断是否需要拦截这次请求（登录登出，front，backend的uri都不需要过滤，不是以上的uri需要进行拦截，通过路径匹配器path—matcher进行比较，返回一个boolean值进行判断）
    	String[] uris = new String[] {
    			"/employee/login",
    			"/employee/logout",
    			"/backend/**",
    			"/front/**",
    			"/common/**",
    			"/user/sendMsg",
    			"/user/login"
    	};
    	boolean checkResult = check(uris, uri);
    	//3. 不需要拦截则放行，否则拦截
    	if (checkResult) {
    		log.info("放行该请求");
    		chain.doFilter(request, response);
    		return;
		} 
    	//4-1. 判断管理端登陆状态，已登录则放行（通过判断request.getSession.getAttribute是否存在判断登录与否）
    	if (request.getSession().getAttribute("employee") != null) {
    		log.info("该用户已登录，放行该请求");
    		Long empId = (Long) request.getSession().getAttribute("employee");
    		BaseContext.setCurrentId(empId);
    		chain.doFilter(request, response);
    		return;
		}
    	//4-2. 判断移动端登陆状态，已登录则放行（通过判断request.getSession.getAttribute是否存在判断登录与否）
    	if (request.getSession().getAttribute("user") != null) {
    		log.info("该用户已登录，放行该请求");
    		Long userId = (Long) request.getSession().getAttribute("user");
    		BaseContext.setCurrentId(userId);
    		chain.doFilter(request, response);
    		return;
		}
    	//5. 未登录则返回未登录结果（未登录结果通过response输出流方式返回一个r对象）*filter没有webMvc功能，只能通过response传值
    	//**注意后端传值回前端时解析数据格式为对象→json，前端传回后端是json→对象
    	log.info("未登录用户，拦截请求");
    	response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    	chain.doFilter(request, response);
    }
    
    private boolean check(String[] uris, String uri) {
    	for (String string : uris) {
			if (pathMatcher.match(string, uri)) {
				return true;
			}
		}
    	return false;
    }
}

